/**
 * <pre>项目名称:LogApp-SpringBoot-Demo 
 * 文件名称:AmqpConfig.java 
 * 包名:com.jk.mq 
 * 创建日期:2017年12月20日下午8:13:47 
 * Copyright (c) 2017, 896670039@qq.com All Rights Reserved.</pre> 
 */
package com.jk.util;

import com.jk.dao.PayUserWalletDao;
import com.jk.service.PayUserWalletService;
import com.jk.service.PayUserWalletServiceImpl;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.rabbitmq.client.Channel;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;

/**
 * Qmqp Rabbitmq
 *
 * http://docs.spring.io/spring-amqp/docs/1.4.5.RELEASE/reference/html/
 *
 * @author lkl
 * @version $Id: AmqpConfig.java, v 0.1 2015年11月01日 下午2:05:37 lkl Exp $
 */

/**
 * 消息生产者
 */
@Configuration
public class AmqpConfig {
    /**
     * 注入到payUserWalletService  将消息队列的消息传到service类的接口 操作数据库
     */
    @Autowired
    private  PayUserWalletService payUserWalletService;



    /*
     @Configuration可理解为用spring的时候xml里面的<beans>标签
     @Bean可理解为用spring的时候xml里面的<bean>标签
     */
    public static final String EXCHANGE   = "spring-boot-exchange";
    public static final String ROUTINGKEY = "spring-boot-routingKey";

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("127.0.0.1:5672");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPublisherConfirms(true); //设置 消息回调 如果业务不需要发送消息确认机制，这句话可直接设置为false
        return connectionFactory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //有不同的回调机制的情况下才设置为原型（也就是多例），如果你的业务就一种回调机制，是可以设置为单例的。
    public RabbitTemplate rabbitTemplate() {
	  /*通过使用RabbitTemplate来对生产者提供API操作*/
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    /**
     * 针对消费者配置
     * 1. 设置交换机类型
     * 2. 将队列绑定到交换机
     *
     *
     FanoutExchange: 将消息分发到所有的绑定队列，无routingkey的概念
     HeadersExchange ：通过添加属性key-value匹配
     DirectExchange:按照routingkey分发到指定队列
     TopicExchange:多关键字匹配
     */
    @Bean
    public DirectExchange defaultExchange() {
        return new DirectExchange(EXCHANGE);
    }

    @Bean
    public Queue queue() {
        return new Queue("spring-boot-queue", true); //设置队列持久 化

    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(defaultExchange()).with(AmqpConfig.ROUTINGKEY);
    }

@Bean
  public SimpleMessageListenerContainer messageContainer() {
      SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
      container.setQueues(queue());
      container.setExposeListenerChannel(true);
      container.setMaxConcurrentConsumers(1);
      container.setConcurrentConsumers(1);
      container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
      container.setMessageListener(new ChannelAwareMessageListener() {

          @Override
          public void onMessage(Message message, Channel channel) throws Exception {
              HashMap map = new HashMap();
              byte[] body = message.getBody();

              Object obj = null;
              try {
                  ByteArrayInputStream bis = new ByteArrayInputStream(body);
                  ObjectInputStream ois = new ObjectInputStream (bis);
                  obj = ois.readObject();
                  ois.close();
                  bis.close();
              } catch (IOException ex) {
                  ex.printStackTrace();
              } catch (ClassNotFoundException ex) {
                  ex.printStackTrace();
              }
              /**
               *将byte[]数组转换成object对象
               * 将object对象转成map
               * 把对象转换成你所需要的类型
               */
              map=(HashMap)obj;
              Double Money =(Double) map.get("money");
              String bankNum =(String) map.get("bankNum");
              String useraccount = (String) map.get("useraccount");
              payUserWalletService.withdrawUserBalanc(Money,bankNum,useraccount);
              channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
          }
      });
      return container;
  }

}
